use actix_web::{App, http, HttpRequest, HttpResponse, HttpServer, Responder, web, Error};
use actix_web::get;
use actix_session::{CookieSession, Session};

mod Application;

use Application::App::ServerInfo;

mod Vo;

use Vo::Form::Info;

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().data(ServerInfo { app_name: String::from("sky blog") })
            .wrap(CookieSession::signed(&[0; 32]).secure(false))
            .route("/", web::get().to(index))
            .service(index2)
            .service(index3)
            .service(index4)
            .service(index5)
    })
        .keep_alive(60)  //默认5s
        //.workers(2)    逻辑cpu<2 线程数调整一下
        .bind("127.0.0.1:8000")?

        .run()
        .await
}


async fn index(data: web::Data<ServerInfo>) -> String {
    let app_name = &data.app_name;
    return format!("Hello {}!", app_name);
}

#[get("/hello")]
async fn index2() -> impl Responder {
    return HttpResponse::Ok().body("hello rust!");
}

//path parameter
#[get("/info/{p1}/{p2}")]
async fn index3(info: web::Path<(String, String)>) -> impl Responder {
    return HttpResponse::Ok().body(format!("hello,{}:{}", info.0, info.1));
}

//request parameter , Option可选来避免不传递报错
#[get("/friend")]
async fn index4(req: HttpRequest, info: web::Query<Info>) -> HttpResponse {
    let name = &info.user_name;
    let email = &info.email.as_ref();
    return HttpResponse::Ok().body(format!("Welcom {:?}!", email.unwrap()));
}

//session 使用
#[get("/index5")]
async fn index5(session: Session) -> Result<HttpResponse, Error> {
    // access session data
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok(HttpResponse::Ok().body(format!(
        "Count is {:?}!",
        session.get::<i32>("counter")?.unwrap()
    )))
}
